<template>
  <addEditEBookView ref="addEditEBookView" />
  <addFileView ref="addFileView" />
  <el-main>
    <div class="app-table">
      <div class="app-body">
        <div class="app-search">
          <el-form :inline="true" class="demo-form-inline" v-model="form">
            <el-form-item label="所在年级" :label-width="formLabelWidth" prop="gradeId">
              <el-select v-model="form.gradeId" autocomplete="off" @change="filterGradeId" style="width:190px;"
                placeholder="请选择所在年级">
                <el-option v-for="gradeId in gradeIds" :key="gradeId" :value="gradeId"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="所在学年" :label-width="formLabelWidth" prop="classId">
              <el-select v-model="form.schoolYear" autocomplete="off" placeholder="请选择所在学年" style="width:190px;">
                <el-option v-for="item in schoolYears" :key="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="考试名称" :label-width="formLabelWidth" prop="classId">
              <el-select v-model="form.typeName" autocomplete="off" placeholder="请选择考试名称" style="width:190px;">
                <el-option v-for="item in types" :key="item.name" :value="item.name"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain @click="onSubmit" @keyup.enter="searchEnter">搜索</el-button>
              <el-button type="warning" plain @click="editbaseAchievement" @keyup.enter="searchEnter">一键成绩分析</el-button>
              <el-button type="success" plain @click="exportToExcel">导出数据</el-button>

            </el-form-item>
          </el-form>
        </div>
        <el-table size="small" :data="list" ref="table" class="custom-table" border
          :header-cell-style="{ 'text-align': 'center', 'border-color': '#444444' }"
          :cell-style="{ 'text-align': 'center', 'border-color': '#444444' }">
          <el-table-column width="66px" prop="modeSubject" sortable label="选考类型" />
          <el-table-column width="85px" prop="teacherName" sortable label="班主任" />
          <el-table-column width="50px" prop="gradeId" label="年级" />
          <el-table-column width="44px" prop="classId" sortable label="班级" />
          <el-table-column width="66px" prop="countStudent" sortable label="统考人数" />
          <el-table-column label="985">
            <el-table-column width="44px" sortable prop="above985" label="指标" />
            <el-table-column width="55px" prop="countAbove985" label="完成数" />
            <el-table-column width="70px" prop="percentageAbove985" label="完成率" sortable>
              <template #default="scope">
                {{ scope.row.percentageAbove985 }}%
              </template>
            </el-table-column>
            <el-table-column width="44px" sortable prop="rankingAbove985" label="名次" />
          </el-table-column>
          <el-table-column label="211">
            <el-table-column width="44px" sortable prop="above211" label="指标" />
            <el-table-column width="55px" sortable prop="countAbove211" label="完成数" />
            <el-table-column width="70px" prop="percentageAbove211" label="完成率" sortable>
              <template #default="scope">
                {{ scope.row.percentageAbove211 }}%
              </template>
            </el-table-column>
            <el-table-column width="44px" sortable prop="rankingAbove211" label="名次" />
          </el-table-column>
          <el-table-column label="重本">
            <el-table-column width="44px" sortable prop="aboveZd" label="指标" />
            <el-table-column width="55px" sortable prop="countAboveZd" label="完成数" />
            <el-table-column width="70px" prop="percentageAboveZd" label="完成率" sortable>
              <template #default="scope">
                {{ scope.row.percentageAboveZd }}%
              </template>
            </el-table-column>
            <el-table-column width="44px" sortable prop="rankingAboveZd" label="名次" />
          </el-table-column>
          <el-table-column label="一本">
            <el-table-column width="44px" sortable prop="aboveYb" label="指标" />
            <el-table-column width="55px" sortable prop="countAboveYb" label="完成数" />
            <el-table-column width="70px" sortable prop="percentageAboveYb" label="完成率">
              <template #default="scope">
                {{ scope.row.percentageAboveYb }}%
              </template>
            </el-table-column>
            <el-table-column width="44px" sortable prop="rankingAboveYb" label="名次" />
          </el-table-column>
          <el-table-column label="综合贡献率">
            <el-table-column width="130px" prop="calculationMethod" label="计算办法" />
            <el-table-column width="70px" sortable prop="percentageContribution" label="结果">
              <template #default="scope">
                {{ scope.row.percentageContribution }}%
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column prop="rankingContribution" sortable label="班级名次" />
          <!-- <el-table-column label="操作" >
            <template #default="scope">
              <el-button
                size="small"
                type="success"
                @click="editEBook(scope.row)"
                >编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteEBook(scope.row.id)"
                >删除
              </el-button>
            </template>
          </el-table-column> -->
          <template v-slot:empty>
            <el-empty description="暂无数据"></el-empty>
          </template>
        </el-table>
        <!-- <el-config-provider :locale="locale">
          <el-pagination
            :total="total"
            :page-size="limit"
            :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="changePageSize"
            @current-change="changeCurrentPage"
          >
          </el-pagination>
        </el-config-provider> -->
      </div>
      <bottomView></bottomView>
    </div>
  </el-main>
</template>
<script>
import addEditEBookView from "@/components/eBook/addEditEBook.vue";
import addFileView from "@/components/addExcelFile.vue";
import { ElConfigProvider, ElMessageBox, ElMessage } from "element-plus";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { httpService } from "@/utils/httpService";
import { Picture as IconPicture, Upload } from "@element-plus/icons-vue";
import bottomView from "@/components/bottom.vue";
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

export default {
  name: "EBookListView",
  data() {
    return {
      gradeIds: [],
      types: [],
      schoolYears: [],
      type: 0,
      title: "",
      page: 0,
      pageSize: 1000,
      total: 0,
      limit: 1000,
      list: [],
      typeList: [],
      form: {
        typeId: "",
        code: "",
        title: "",
        press: "",
        author: "",
        imageUrl: "",
        gradeId: "",
        classId: "",
        schoolYear: "",
        typeName: "",
      },
    };
  },
  components: {
    XLSX, saveAs,
    addEditEBookView,
    addFileView,
    IconPicture,
    ElConfigProvider,
    ElMessageBox,
    ElMessage,
    Upload,
    bottomView,
  },
  setup() {
    return {
      locale: zhCn,
    };
  },
  mounted() {
    this.getGradeIds();
    this.getEBookList();
    this.getEBookTypeList();
  },
  watch: {
    $route() {
      this.getEBookList();
      this.getEBookTypeList();
    },
  },
  methods: {
    exportToExcel() {
      const worksheet = XLSX.utils.table_to_sheet(this.$refs.table.$el);

      // Apply cell styles
      const range = XLSX.utils.decode_range(worksheet['!ref']);
      for (let R = range.s.r; R <= range.e.r; ++R) {
        for (let C = range.s.c; C <= range.e.c; ++C) {
          const cellAddress = XLSX.utils.encode_cell({ r: R, c: C });
          const cell = worksheet[cellAddress];
          if (cell) {
            cell.s = {
              alignment: { horizontal: 'center' },
              border: {
                top: { style: 'thin', color: { rgb: 'FF0000' } },
                bottom: { style: 'thin', color: { rgb: 'FF0000' } },
                left: { style: 'thin', color: { rgb: 'FF0000' } },
                right: { style: 'thin', color: { rgb: 'FF0000' } }
              }
            };
          }
        }
      }

      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, '班级完成率');
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
      saveAs(data, this.form.gradeId + "级" + this.form.schoolYear + this.form.typeName + '班级完成率.xlsx');
    }

    ,
    editbaseAchievement(obj) {
      ElMessageBox.confirm("确定要执行成绩分析吗？", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let formData = new FormData();
          formData.append("schoolYear", this.form.schoolYear)
          formData.append("typeName", this.form.typeName)
          formData.append("gradeId", this.form.gradeId)
          httpService(
            "/javaApi/baseAchievementAnalysis/queryClassFinishPercentage",
            formData,
            "post"
          ).then((data) => {
            if (data.code == 200) {
              ElMessage.success(data.message);
              this.getEBookList()
            } else {
              ElMessage.error("执行失败，请重试！");
            }
          });
        })
        .catch(() => { });
    },

    getGradeIds() {
      let date = new Date();
      let nowYear = parseInt(date.getFullYear());
      let nowMonth = parseInt(date.getMonth());
      let gradeIds = [];
      if (nowMonth > 6) {
        gradeIds.push(nowYear - 2);
        gradeIds.push(nowYear - 1);
        gradeIds.push(nowYear);
      } else {
        gradeIds.push(nowYear - 3);
        gradeIds.push(nowYear - 2);
        gradeIds.push(nowYear - 1);
      }
      this.gradeIds = gradeIds;
      this.form.gradeId = gradeIds[0]
      this.getSchoolYears();
      this.getAchievementTypeList();
    },
    getAchievementTypeList() {
      httpService("/javaApi/achievementType/list/1/1000", {}, "get").then(
        (data) => {
          this.types = data.list;
          this.form.typeName = this.types[0].name
        }
      );
    },
    getSchoolYears() {
      let date = new Date();
      let nowYear = parseInt(date.getFullYear());
      let nowMonth = parseInt(date.getMonth());
      let schoolYears = [];
      if (nowMonth > 6) {
        // 2023
        schoolYears.push(nowYear - 2000 + "-" + (nowYear - 1999) + "学年上");
        schoolYears.push(nowYear - 2001 + "-" + (nowYear - 2000) + "学年下");
        schoolYears.push(nowYear - 2001 + "-" + (nowYear - 2000) + "学年上");
        schoolYears.push(nowYear - 2002 + "-" + (nowYear - 2001) + "学年下");
        schoolYears.push(nowYear - 2002 + "-" + (nowYear - 2001) + "学年上");
      } else {
        schoolYears.push(nowYear - 2001 + "-" + (nowYear - 2000) + "学年下");
        schoolYears.push(nowYear - 2001 + "-" + (nowYear - 2000) + "学年上");
        schoolYears.push(nowYear - 2002 + "-" + (nowYear - 2001) + "学年下");
        schoolYears.push(nowYear - 2002 + "-" + (nowYear - 2001) + "学年上");
        schoolYears.push(nowYear - 2003 + "-" + (nowYear - 2002) + "学年下");
        schoolYears.push(nowYear - 2003 + "-" + (nowYear - 2002) + "学年上");
      }
      this.schoolYears = schoolYears;
      this.form.schoolYear = schoolYears[0]
    },
    getEBookTypeList() {
      httpService("/javaApi/eBookType/list/1/1000", {}, "get").then((data) => {
        this.typeList = data.object.list;
      });
    },
    searchEnter: function (e) {
      // 使用 which 和 keyCode 属性来解决兼容问题
      var keyCode = window.event ? e.keyCode : e.which;
      var val = e.target.value;
      if (keyCode == 13 && val) {
        this.getEBookList();
      }
    },
    add() {
      this.$refs.addEditEBookView.title = "添加电子期刊";
      this.$refs.addEditEBookView.typeList = this.typeList;
      this.$refs.addEditEBookView.dialogFormVisible = true;
    },
    editEBook(obj) {
      this.$refs.addEditEBookView.title = "修改信息";
      this.$refs.addEditEBookView.getEBookById(obj.id);
      this.$refs.addEditEBookView.dialogFormVisible = true;
    },
    deleteEBook(id) {
      ElMessageBox.confirm("确定要删除本条记录吗？", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          httpService("/javaApi/eBook/deleteById", "id=" + id, "post").then(
            (data) => {
              if (data.code == 200) {
                ElMessage.success(data.message);
                this.getEBookList();
              } else {
                ElMessage.error(data.message);
              }
            }
          );
        })
        .catch(() => { });
    },
    reloadData() {
      this.page = 1;
      this.getEBookList();
    },
    importExcel() {
      this.$refs.addFileView.dialogFormVisible = true;
      this.$refs.addFileView.title = "批量导入电子期刊";
      this.$refs.addFileView.uploadApiUrl = "/javaApi/eBook/importExcel";
    },
    exportExcel() {
      httpService(
        "/javaApi/eBook/exportExcel",
        {
          code: this.form.code,
          title: this.form.title,
          press: this.form.press,
          author: this.form.author,
          typeId: this.form.typeId,
          imageUrl: this.form.imageUrl,
        },
        "get"
      ).then((data) => {
        if (data.code == 200) {
          window.open(data.message, "_blank");
        }
      });
    },
    onSubmit() {
      this.getEBookList();
    },
    // 每页记录数改变，size：回调参数，表示当前选中的“每页条数”
    changePageSize(size) {
      this.pageSize = size;
      this.limit = size;
      this.getEBookList();
    },

    // 改变页码，page：回调参数，表示当前选中的“页码”
    changeCurrentPage(page) {
      this.page = page;
      this.getEBookList();
    },
    tableRowClassName({ row, rowIndex }) {
      return "";
    },
    getEBookList() {
      httpService(
        "/javaApi/baseAchievementAnalysis/list/" + this.page + "/" + this.pageSize,
        {
          schoolYear: this.form.schoolYear,
          typeName: this.form.typeName,
          gradeId: this.form.gradeId,
          classId: this.form.classId,
        },
        "get"
      ).then((data) => {
        console.log(data)
        this.list = data.list;
        this.total = data.total;
        this.pageCount = data.pages;
      });
    },
  },
};
</script>
<style scoped>
.custom-table {
  border: 1px solid #444444;
  /* Set the border color for the el-table */
}

.el-main {
  padding: 0px;
  text-align: left;
}

.teacher-content {
  width: 100%;
}

.app-table {
  background: #eff3f5;
  padding: 10px;
}

.app-separator {
  padding-top: 10px;
  padding-bottom: 20px;
  padding-left: 10px;
}

.app-body {
  background: white;
  padding: 20px 20px 10px 20px;
  margin-bottom: 10px;
  min-height: calc(100vh - 243px);
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-lighter);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-lighter);
}

.el-pagination {
  text-align: center;
  margin-top: 10px;
}
</style>
